package com.teach.config.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.teach.config.ConfigProperties;
import com.teach.service.UserService;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SimulateLoginInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private ConfigProperties config;

	@Autowired
	private UserService service;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (config.simulateLogin.enable) {
			if (request.getSession().getAttribute("user") == null) {
				try {
					request.getSession().setAttribute("user",
							service.login(config.simulateLogin.userName, config.simulateLogin.userPwd));
				} catch (Exception ex) {
					log.warn("模拟登陆失败！", ex);
				}
			}
		}
		return true;
	}
}
